# -*- coding: utf-8 -*-
import os
#关闭fetchurl，让httplib直接使用socket服务来连接
os.environ['disable_fetchurl'] = "1" 
import sys   
import time #import time, gmtime, strftime, localtime
from datetime import datetime
import traceback
import httplib
import urllib 
import urllib2
# 打开urllib2的debug开关
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPSHandler(1)))

import hashlib
import json
import string
import base64
import cPickle

from bottle import *
from bottle import __version__ as bottleVer

#from auth import _query2dict, _chkQueryArgs

from utility import INCR4KV as __incr
from utility import TSTAMP, GENID, USRID, DAMAID
from utility import ADD4SYS
from utility import PUT2SS

#from utility import WxApp

#from md import INITlogF,GOTallLog

#print sys.path
from config import CFG
from xsettings import XCFG

debug(True)
APP = Bottle()

@APP.put('/log')
def put_log4cli():
    _msg = request.forms.get('log').decode('utf8')
    print _msg
    #return None
    tag, log = _msg.split(CFG.GAP0)
    _tli = KV.get(CFG.K4D['tag'])

    if tag not in _tli:
        _tli.append(tag)
        KV.set(CFG.K4D['tag'], _tli)


    if 0 == len(log):
        print "EMPTY msg."
    else:
        _pli = KV.get(CFG.K4D['p'])
        log_id = GENID('p')
        _pli.append(log_id)
        #print _pli
        KV.set(CFG.K4D['p'], _pli)
        KV.set(log_id, _msg.encode('utf8'))

    return "200,%s\n\n"%log



@APP.get('/log')
def log_cli():
    _tag = CFG.TAG0
    _pli = KV.get(CFG.K4D['p'])
    print _pli
    _exp = {}
    hislog = []
    for k in _pli:
        _msg = KV.get(k)
        #print _msg.split(CFG.GAP0)[1]
        hislog.append(_msg) #.split(CFG.GAP0)[1]
    #return hislog
    #hislog.sort(reverse=True)
    _exp['logs'] = hislog
    return _exp
    #return GOTallLog()

@APP.get('/log/<tag>')
def log_tag_cli(tag):
    _tag = tag
    _pli = KV.get(CFG.K4D['p'])
    print _pli
    hislog = ""
    for k in _pli:
        hislog += "\n"+KV.get(k)

    return hislog
    #return GOTallLog()
@APP.get('/log/lt')
def list_tag_cli():
    print 'list all TAGs'
    _tli = KV.get(CFG.K4D['tag'])
    print _tli
    return "\n".join(_tli[1:])
    #return GOTallLog()
@APP.post('/log')
def log_cli_post():
    log = request.forms.get('log').decode('utf8')
    if "FLUSH" == log:
        print "clean all!"
        _flush_kvdb()



def _flush_kvdb():
    for k in CFG.K4D:
        if 'incr' == k:
            #KV.delete(CFG.K4D[k])
            KV.set(CFG.K4D[k], 42)
            print CFG.K4D[k], KV.get(CFG.K4D[k])
        elif 'tag' == k:
            KV.set(CFG.K4D[k], ['NULL'])
            print CFG.K4D[k], KV.get(CFG.K4D[k])
        elif 'p' == k:
            pli = KV.get(CFG.K4D[k])
            for p in pli:
                print "deleted", p
                KV.delete(p)
            #KV.delete(CFG.K4D[k])
            KV.set(CFG.K4D[k], [])
            print CFG.K4D[k], KV.get(CFG.K4D[k])
        else:
            #KV.delete(CFG.K4D[k])
            KV.set(CFG.K4D[k], [])
            print CFG.K4D[k], KV.get(CFG.K4D[k])

#@view('404.html')
@APP.error(404)
def error404(error):
    return '''


\          SORRY            /
 \                         /
  \    This page does     /
   ]   not exist yet.    [    ,'|
   ]                     [   /  |
   ]___               ___[ ,'   |
   ]  ]\             /[  [ |:   |
   ]  ] \           / [  [ |:   |
   ]  ]  ]         [  [  [ |:   |
   ]  ]  ]__     __[  [  [ |:   |
   ]  ]  ] ]\ _ /[ [  [  [ |:   |
   ]  ]  ] ] (#) [ [  [  [ :===='
   ]  ]  ]_].nHn.[_[  [  [
   ]  ]  ]  HHHHH. [  [  [
   ]  ] /   `HH("N  \ [  [
   ]__]/     HHH  "  \[__[
   ]         NNN         [
   ]         N/"         [
   ]         N H         [
  /          N            \

/                           \

roaring zoomquiet+404@gmail.com
'''
#    return template('404.html')

@APP.route('/favicon.ico')
def favicon():
    abort(204)
    
@APP.route('/static/<filename>')
def server_static(filename):
    return static_file(filename, root='static')
    






